import mqtt from './mqtt.min.js'

export default {
	data() {
		return {
			mqttClient: null, // MQTT客户端实例
			mqttConnected: false, // 是否已连接到MQTT服务器
			mqttMessage: '', // 接收到的MQTT消息
			mqttOptions: { // MQTT连接选项
				//protocol: 'ws',
				protocol: 'wx',
				host: '121.37.163.90',
				port: 9001,
				endpoint: '/mqtt',

				//小程序 参考：https://ext.dcloud.net.cn/plugin?id=854  如果你的小程序真机连不上，在emq的配置中加上一句： listeners.ws.default.websocket.fail_if_no_subprotocol = false  注意你的emq版本要在4.4以上
				username: 'admin',
				password: 'admin123',
				clientId: 'MyClientId_' + Math.random().toString(16).substr(2, 8),
				keepalive: 60,
				clean: true,
				connectTimeout: 5 * 1000, // ms
				reconnectPeriod: 2000, // ms
				mqttVersion: 4,

			},
			mqttSubscriptions: [{
				topic: 'PM20PG_at/topic',
				qos: 0,
			}],
		}
	},
	onLaunch: function() {
		console.log('App Launch');
		uni.hideTabBar();
		// #ifdef APP-PLUS
		plus.screen.lockOrientation("portrait-primary");
		// #endif
	},
	onShow: function() {
		uni.hideTabBar();
		console.log('App Show');
		try {
			const network = this.$gStore.state.bind.mobile.isConnected;
			//console.log('network.isConnected=' + network);
			if (network) {
				this.$glzShadow.reconnectToMQTT();
			}
		} catch (e) {
			console.log('App onShow error: ' + e);
		}
	},
	onHide: function() {
		console.log('App Hide');
		try {
			this.$glzShadow.destroy(true, () => {
				console.log('mqtt closed.')
			});
		} catch (e) {
			console.log('App onHide error: ' + e);
		}
	},
	methods: {
		//连接MQTT服务器
		mqttConnect() {

			try {
				if (!this.mqttConnected) {
					const {
						protocol,
						host,
						port,
						endpoint,
						...options
					} = this.mqttOptions
					let connectUrl = `${protocol}://${host}:${port}${endpoint}`
					console.log('MQTT connecting', connectUrl, options)
					this.mqttClient = mqtt.connect(connectUrl, options)

					// const options = {
					// 	port: 9001,
					// 	connectTimeout: 4000,
					// 	clientId: 'MyClientId_' + Math.random().toString(16).substr(2, 8)
					// };
					// this.mqttClient = mqtt.connect("wx://120.25.155.46:9001/mqtt", options);

					this.mqttClient.on('connect', () => {
						try {
							this.mqttMessage = '连接成功';
							console.log('MQTT connected')
							this.$u.toast('连接成功');
							//需要安装到手机上进行测试，需要打印信息，但是手机上运行看不见，所以改为提示
							uni.showToast({
								title: '连接成功',
								icon: 'none'
							});

							this.mqttConnected = true
							// 恢复订阅
							// this.mqttSubscriptions.forEach(topic => {
							//     this.mqttClient.subscribe(topic)
							// })
							this.mqttSubscribeInit();
						} catch (e) {
							console.log('App onShow error: ' + e);
						}
					})
					this.mqttClient.on('reconnect', () => {
						try {
							this.mqttMessage = '重新连接';
							console.log('MQTT reconnect')
						} catch (e) {
							console.log('App onShow error: ' + e);
						}

					})
					this.mqttClient.on('close', () => {
						try {
							this.mqttMessage = '连接关闭';
							console.log('MQTT disconnected')
							this.mqttConnected = false
						} catch (e) {
							console.log('App onShow error: ' + e);
						}
					})

					this.mqttClient.on('message', (topic, message) => {
						try {
							this.mqttMessage = message.toString();
							console.log(`MQTT message received: ${message.toString()} from topic ${topic}`)
							//将接收到的消息转化成json格式
							let msg = JSON.parse(message.toString());
							//触发事件
							this.$emit('mqtt-message', msg);
						} catch (e) {
							console.log('App onShow error: ' + e);
						}
					})
				}
			} catch (e) {
				console.log('App onHide error: ' + e);
			}

		},
		//断开MQTT连接
		mqttDisconnect() {
			if (this.mqttConnected) {
				this.mqttClient.end()
				this.mqttConnected = false
				this.mqttSubscriptions = []
			}
		},
		//订阅指定主题
		mqttSubscribe(topicObj) {
			if (this.mqttConnected) {
				const {
					topic,
					qos
				} = topicObj
				this.mqttClient.subscribe(topic, {
					qos
				}, (error, res) => {
					if (error) {
						console.log('Subscribe to topics error', error)
						return
					}
					console.log('Subscribe to topics res', res)
				})
			}
		},
		//订阅mqttSubscriptions中初始主题
		mqttSubscribeInit() {
			if (this.mqttConnected) {
				this.mqttSubscriptions.forEach((topic) => {
					this.mqttSubscribe(topic)
				})
			}
		},
		//取消订阅指定主题
		mqttUnsubscribe(topic) {
			if (this.mqttConnected) {
				this.mqttClient.unsubscribe(topic)
				const index = this.mqttSubscriptions.indexOf(topic)
				if (index !== -1) {
					this.mqttSubscriptions.splice(index, 1)
					console.log(`Unsubscribed from ${topic}`)
				}
			}
		},
		//取消订阅所有主题
		mqttUnsubscribeAll() {
			if (this.mqttConnected) {
				this.mqttSubscriptions.forEach(topic => {
					this.mqttClient.unsubscribe(topic)
				})
				this.mqttSubscriptions = []
			}
		},
	},
	created() {
		console.log("智能药盒 mqtt");
		this.mqttConnect();
	},
	beforeDestroy() {
		this.mqttUnsubscribeAll();
		this.mqttDisconnect();
	}
}